package logic

import (
	"context"
	"fmt"
	"gozeroProject/api/internal/svc"
	"gozeroProject/api/internal/types"
	"gozeroProject/rpc/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type SearchUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSearchUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchUserLogic {
	return &SearchUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SearchUserLogic) SearchUser(req *types.SearchUserRequest) (resp *types.SearchUserResponse, err error) {
	// 根据请求参数查询用户

	users, err := l.svcCtx.UserRpc.SearchUser(l.ctx, &user.SearchUserReq{
		UserId: req.UserId,
		Name:   req.Name,
	})

	if err != nil {
		return nil, fmt.Errorf("failed to search user: %w", err)
	}

	response := &types.SearchUserResponse{
		List: make([]types.UserReply, len(users.List)),
	}

	// 将查询结果映射到 UserReply 结构体
	for i, user := range users.List {
		response.List[i] = types.UserReply{
			ID:       int(user.ID),
			UserId:   user.UserId,
			Name:     user.Name,
			Mobile:   user.Mobile,
			Gender:   user.Gender,
			Nickname: user.Nickname,
			Type:     int(user.Type),
		}
	}

	return response, nil
}
